import 'dart:async';

import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:flutter/material.dart';
import 'package:flutter_rtk/common/assets.dart';
import 'package:flutter_rtk/common/common.dart';
import 'package:flutter_rtk/common/constants.dart';
import 'package:flutter_rtk/models/app_model.dart';
import 'package:flutter_rtk/pages/home/index.dart';
import 'package:flutter_rtk/pages/mine/index.dart';
import 'package:flutter_rtk/pages/tools/index.dart';
import 'package:flutter_rtk/service/connectivity_service.dart';
import 'package:flutter_rtk/service/event_bus_service.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:provider/provider.dart';

/// app tabbar build
class AppPage extends StatefulWidget {
  const AppPage({super.key});

  @override
  State<AppPage> createState() => _AppPageState();
}

class _AppPageState extends State<AppPage> {
  late PageController controller;
  late StreamSubscription _subscription;

  // tabbar list
  List<Widget> bottomBarList = const [HomePage(), ToolsPage(), MinePage()];

  // tabbar list label
  List bottomBarConfigs = [
    {"icon": "home", "label": '首页'},
    {"icon": "tools", "label": '工具'},
    {"icon": "mine", "label": '我的'},
  ];

  @override
  void initState() {
    super.initState();
    var appModel = context.read<AppModel>();
    controller = PageController(initialPage: appModel.currentIdx);
    appModel.initController(controller);
    // 网络监控
    _subscription = Connectivity().onConnectivityChanged.listen((ConnectivityResult result) {
      // showToast("网络环境变为:${result.name}");
      if (result == ConnectivityResult.none) {
        ConnectivityService.to.isOnline = false;
      } else {
        ConnectivityService.to.isOnline = true;
      }
    });
  }

  @override
  void dispose() async {
    controller.dispose();
    EventBusService.remove();
    _subscription.cancel();
    super.dispose();
  }

  Widget _buildMainView() {
    return Scaffold(
      backgroundColor: Colors.white,
      body: PageView(
        controller: controller,
        physics: const NeverScrollableScrollPhysics(), // 禁止左右滚动
        children: bottomBarList,
      ),
      bottomNavigationBar: Consumer<AppModel>(builder: (context, app, child) {
        return BottomNavigationBar(
          type: BottomNavigationBarType.fixed,
          backgroundColor: Colors.white,
          elevation: 5,
          onTap: (index) {
            context.read<AppModel>().changeCurrentIdx(index);
          },
          selectedFontSize: 24.sp,
          unselectedFontSize: 24.sp,
          selectedItemColor: AppConstants.brandColor,
          unselectedItemColor: const Color(0xFF666666),
          selectedIconTheme: const IconThemeData(color: AppConstants.brandColor),
          unselectedIconTheme: const IconThemeData(color: Color(0xFF3E3A39)),
          currentIndex: app.currentIdx,
          items: bottomBarConfigs.map((e) => _buildBottomBarItem(e['icon'], e['label'])).toList(),
        );
      }),
    );
  }

  /// 构建底部bar item
  BottomNavigationBarItem _buildBottomBarItem(String icon, String label) {
    return BottomNavigationBarItem(
      icon: SizedBox(width: 45.w, height: 45.h, child: Image.asset(AppAssets.tabbarUnselect.replaceAll("%s", icon))),
      activeIcon: SizedBox(width: 45.w, height: 45.h, child: Image.asset(AppAssets.tabbarSelected.replaceAll("%s", icon))),
      label: label,
    );
  }

  @override
  Widget build(BuildContext context) {
    return _buildMainView();
  }
}
